package com.sch.wanandroid.ui.set

import android.app.Application
import androidx.lifecycle.*
import com.sch.wanandroid.WanAndroidApplication
import com.sch.wanandroid.network.NetWorkManager
import com.sch.wanandroid.util.CacheDataManager
import kotlinx.coroutines.*
import java.lang.Exception

/**
 * Created by Sch.
 * Date: 2020/12/15
 * description:
 */
class SetViewModel(application: Application) : AndroidViewModel(application) {
    private val _logoutSuccess = MutableLiveData<Boolean>()
    val logoutSuccess: LiveData<Boolean> = _logoutSuccess

    private val _clearCacheSuccess = MutableLiveData<Boolean>()
    val clearCacheSuccess: LiveData<Boolean> = _clearCacheSuccess

    private val _updataSuccess = MutableLiveData<Boolean>()
    val updataSuccess: LiveData<Boolean> = _updataSuccess

    private val _errorMsg = MutableLiveData<String?>()
    val errorMsg: LiveData<String?> = _errorMsg

    fun logout() {
        viewModelScope.launch {
            try {
                val result = NetWorkManager.apiService.doLogOut()
                if (result.errorCode != 0) {
                    _errorMsg.value = result.errorMsg
                } else {
                    _logoutSuccess.value = true
                }
            } catch (e: Exception) {
                _errorMsg.value = e.toString()
            }
        }
    }

    fun clearCache() {
        viewModelScope.launch {
            async {
                CacheDataManager.clearAllCache(getApplication())
            }.await()
            _clearCacheSuccess.value = true
        }
    }

    fun checkUpdate() {
        viewModelScope.launch {
            withContext(Dispatchers.Default) {
                delay(1400)
            }
            _updataSuccess.value = true
        }
    }

}